package com.compty.paint.web.member;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.compty.core.framework.context.spring.SpringContextHolder;
import com.compty.core.framework.util.FileUtil;
import com.compty.core.framework.util.PropertiesUtil;
import com.compty.core.page.Page;
import com.compty.core.struts2.BaseAction;
import com.compty.paint.domain.CatalogType;
import com.compty.paint.domain.ImageInfo;
import com.compty.paint.domain.Painter;
import com.compty.paint.domain.Painting;
import com.compty.paint.manager.CatalogTypeManager;
import com.compty.paint.manager.ImageInfoManager;
import com.compty.paint.manager.PaintingManager;
import com.compty.paint.service.impl.PainterService;
import com.compty.paint.service.impl.PaintingService;
import com.compty.paint.util.Constants;

@SuppressWarnings("unchecked")
public class SystemManagerAction extends BaseAction{
	
	private static final long serialVersionUID = -2993398906796118673L;
	private static Log logger = LogFactory.getLog(SystemManagerAction.class);
	
	public String view_Audit_Mode(){
		
		request.setAttribute("audit_mode_painting", Constants.Auto_Audit);
		
	    request.setAttribute("audit_mode_member", Constants.Member_Audit);
		
		return "audit_mode";
	}
	
	/**
	 * 设置作品、艺术家、展览、拍卖 审核模式
	 */
	public String changeAuditMode_painting(){
		
		String auditMode = request.getParameter("auditMode");
		
		if("1".equals(auditMode)){
			PropertiesUtil.writePropertyValue("conf/conf.properties", "painting_audit", "true");
			Constants.Auto_Audit = true ;
		}else if("0".equals(auditMode)){
			PropertiesUtil.writePropertyValue("conf/conf.properties", "painting_audit", "false");
			Constants.Auto_Audit = false ;
		}
		
		request.setAttribute("ajaxData", "0000");
		
		return "changeAuditMode_painting";
	}
	
	/**
	 * 设置会员审核模式
	 */
	public String changeAuditMode_member(){
		
		String auditMode = request.getParameter("auditMode");
		
		if("1".equals(auditMode)){
			PropertiesUtil.writePropertyValue("conf/conf.properties", "member_audit", "true");
			Constants.Member_Audit = true ;
		}else if("0".equals(auditMode)){
			PropertiesUtil.writePropertyValue("conf/conf.properties", "member_audit", "false");
			Constants.Member_Audit = false ;
		}
		
		request.setAttribute("ajaxData", "0000");
		
		return "changeAuditMode_member";
	}
	
	/***重新发布瓷器频道图片***/
	public String publishCiyiPictures() throws Exception{
		PaintingManager paintingManager = SpringContextHolder.getBean("paintingManager");
		ImageInfoManager imageInfoManager = SpringContextHolder.getBean("imageInfoManager");
		Page page = paintingManager.findCiYiByPage(1,20,null);
		int pageCount = page.getPageCount();
		for (int j =  1; j <= pageCount; j++) {
			page = paintingManager.findCiYiByPage(j,20,null);
			List<Painting>  paintings= (List<Painting>) page.getResult();
			for (Painting painting : paintings) {
				if(painting.getImageInfo() != null){
					ImageInfo img = imageInfoManager.get(painting.getImageInfo().getId());
					generateImageOfPaintingFirstTime(painting,img);
				}
				if(painting.getImageInfo2() != null){
					ImageInfo img = imageInfoManager.get(painting.getImageInfo2().getId());
					generateImageOfPaintingFirstTime(painting,img);
				}
				if(painting.getImageInfo3() != null){
					ImageInfo img = imageInfoManager.get(painting.getImageInfo3().getId());
					generateImageOfPaintingFirstTime(painting,img);
				}
				if(painting.getImageInfo4() != null){
					ImageInfo img = imageInfoManager.get(painting.getImageInfo4().getId());
					generateImageOfPaintingFirstTime(painting,img);
				}
			}
		}
		request.setAttribute("ajaxData", "{flag:0000,message:\"生成作品图片成功。\"}");
		
		return "generatePicSuccess";
	}
	
	/***重新发布书画频道图片***/
	public String publishShuhuaPictures() throws Exception{
		PaintingManager paintingManager = SpringContextHolder.getBean("paintingManager");
		ImageInfoManager imageInfoManager = SpringContextHolder.getBean("imageInfoManager");
		Page page = paintingManager.findShuhuaByPage(1,20,null);
		int pageCount = page.getPageCount();
		for (int j =  1; j <= pageCount; j++) {
			page = paintingManager.findShuhuaByPage(j,20,null);
			List<Painting>  paintings= (List<Painting>) page.getResult();
			for (Painting painting : paintings) {
				if(painting.getImageInfo() != null){
					ImageInfo img = imageInfoManager.get(painting.getImageInfo().getId());
					generateImageOfPaintingFirstTime(painting,img);
				}
				if(painting.getImageInfo2() != null){
					ImageInfo img = imageInfoManager.get(painting.getImageInfo2().getId());
					generateImageOfPaintingFirstTime(painting,img);
				}
				if(painting.getImageInfo3() != null){
					ImageInfo img = imageInfoManager.get(painting.getImageInfo3().getId());
					generateImageOfPaintingFirstTime(painting,img);
				}
				if(painting.getImageInfo4() != null){
					ImageInfo img = imageInfoManager.get(painting.getImageInfo4().getId());
					generateImageOfPaintingFirstTime(painting,img);
				}
			}
		}
		request.setAttribute("ajaxData", "{flag:0000,message:\"生成作品图片成功。\"}");
		
		return "generatePicSuccess";
	}
	
	/**
	 * 
	 *@Todo:生成全部图片(旧图片移植)
	 */
	public String generatePictureOfPainting(){
		
		try {
			generatePainterImage();
			generatePaintingImage();
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.setAttribute("ajaxData", "{flag:0000,message:\"生成作品图片成功。\"}");
		
		return "generatePicSuccess";
	}
	
	/**
	 * 生成名家名画头像及作品(旧图片移植)
	 */
	public String generateMjmh() throws Exception {
		PainterService painterService =  new PainterService();
		PaintingService paintingService = new PaintingService();
		List<Painter> painterList = painterService.getAllPainterStar();
		
		for (Painter painter : painterList) {
			ImageInfo imageInfo = painter.getImageInfo();
			String destPath= writeImageinfo(painter.getImageInfo(), getImageGeneratePath()+"/painter/"+imageInfo.getId()+"."+ imageInfo.getSuffix());
			String smallImgPath = getImageGeneratePath()+"/painter/"+imageInfo.getId() +"_s."+ imageInfo.getSuffix() ;
			if(destPath == null){
				logger.info("painter image is null =="+painter.getId());
			}else{
				logger.info("destpath===="+destPath);
				logger.info("smallImgPath===="+smallImgPath);
				writePainterSmallImage(destPath, smallImgPath);
			}
			
			List<Painting>  paintingList = paintingService.findPaintingsByPainterId(painter.getId());
			publishPainting(paintingList);
		}
		
		return "generatePicSuccess";
	}
	
	/**
	 * 生成瓷器作品图片(旧图片移植)
	 */
	public String generateCiyi() throws Exception {
		PaintingService paintingService = new PaintingService();
		Page page = paintingService.pagedQuery(1, pageSize,3);
		int pageCount = page.getPageCount();
		for (int i = 1; i <= pageCount; i++) {
			page = paintingService.pagedQuery(i, pageSize,3);
			Object result = page.getResult();
			List<Painting> paintingList = (List<Painting>)result;
			publishPainting(paintingList);
		}
		System.gc();
		
		return "generatePicSuccess";
	}
	
	/**
	 * 
	 *@Todo:生成全部图片(旧图片移植)
	 */
	public String generateSmallPicture(){
		
		try {
			PaintingManager paintingManager = SpringContextHolder.getBean("paintingManager");
			String[] catalog_id = {"1","2","3","4"};
			for (int j = 0; j < catalog_id.length; j++) {
				Page page = paintingManager.findAvailablePaintingsByPage(1, pageSize, catalog_id[j]);
				int pageCount = page.getPageCount();
				for (int i = 1; i <= pageCount; i++) {
					page = paintingManager.findAvailablePaintingsByPage(i, pageSize,catalog_id[j]);
					Object result = page.getResult();
					List<Painting> paintingList = (List<Painting>)result;
					for (Painting painting : paintingList) {
						writeSmallImageinfo(painting,painting.getImageInfo());
						writeSmallImageinfo(painting,painting.getImageInfo2());
						writeSmallImageinfo(painting,painting.getImageInfo3());
						writeSmallImageinfo(painting,painting.getImageInfo4());
					}
				}
			}

			System.gc();
		} catch (Exception e) {
			e.printStackTrace();
		}
		request.setAttribute("ajaxData", "{flag:0000,message:\"生成作品图片成功。\"}");
		
		return "generatePicSuccess";
	}
	
	/**
	 * 生成画家头像(旧图片移植)
	 */
	private void generatePainterImage() throws Exception{
		PainterService painterService =  new PainterService();
		List<Painter> painterList = painterService.getAll();
		
		for (Painter painter : painterList) {
			ImageInfo imageInfo = painter.getImageInfo();
			String destPath= writeImageinfo(painter.getImageInfo(), getImageGeneratePath()+"/painter/"+imageInfo.getId()+"."+ imageInfo.getSuffix());
			String smallImgPath = getImageGeneratePath()+"/painter/"+imageInfo.getId() +"_s."+ imageInfo.getSuffix() ;
			if(destPath == null){
				logger.info("painter image is null =="+painter.getId());
			}else{
				logger.info("destpath===="+destPath);
				logger.info("smallImgPath===="+smallImgPath);
				writePainterSmallImage(destPath, smallImgPath);
			}
		}
	}
	
	/**
	 * 生成所有作品图片、作品缩略图及证书图片(旧图片移植)
	 */
	private void generatePaintingImage() throws Exception{
		PaintingService paintingService = new PaintingService();
		Page page = paintingService.pagedQuery(1, pageSize,null);
		int pageCount = page.getPageCount();
		for (int i = 1; i <= pageCount; i++) {
			page = paintingService.pagedQuery(i, pageSize,null);
			Object result = page.getResult();
			List<Painting> paintingList = (List<Painting>)result;
			publishPainting(paintingList);
		}
		System.gc();
	}
	
	/**
	 * 生成作品图片、作品缩略图及证书图片
	 */
	private void publishPainting(List<Painting> paintingList) throws Exception {
		for (Painting painting : paintingList) {
			writeImageinfo(painting);
			writeZhengshu(painting);
		}
		paintingList.clear();
	}
	
	/***
	 * 生成证书图片
	 */
	private void writeZhengshu(Painting painting) throws Exception {
		ImageInfo imageInfo = painting.getZhengshu();
		if(imageInfo == null) return ;
		
		String absolutePath  = getImageGeneratePath();
		long image_id = imageInfo.getId();
		String suffix = imageInfo.getSuffix();
		String originalImgPath = absolutePath +"/"+Constants.zhengshuFlag+"/"+image_id+"."+suffix;
		writeImageinfo(imageInfo, originalImgPath);
	}
	
	/**
	 * 生成名种缩略图
	 * @param painting 图片Bean
	 */
	private void writeImageinfo(Painting painting) throws Exception {
		ImageInfo imageInfo = painting.getImageInfo();
		if(imageInfo == null) return ;
		
    	Long sharpId = imageInfo.getSharpId();
		long image_id = imageInfo.getId();
		String suffix = imageInfo.getSuffix();
		
		CatalogType catalogType = painting.getCatalogType();
		Painter painter = painting.getPainter();
		String absolutePath  = getImageGeneratePath();
		if( catalogType != null){
			if( 1 == catalogType.getId() ||  2 == catalogType.getId()){
				String foldName = "";
				if( painter != null ){
					if( "2".equals(painter.getType())){//名家名画
						foldName = "/painting/"+painter.getId()+"/";
						String originalImgPath = absolutePath +foldName+image_id+"."+suffix ;//原图
						String middleImgAPath = absolutePath+foldName+image_id +"_m_a."+suffix ;//列表页面中图
						String smallImgPath = absolutePath+foldName+image_id +"_s."+ suffix ;//小图
						logger.info("originalImgPath==="+originalImgPath);
						writeImageinfo(imageInfo, originalImgPath);
						writeMiddleImageA(originalImgPath, middleImgAPath,sharpId);
						writeSmallImage(originalImgPath, smallImgPath,sharpId);
						return;
					}else{
						foldName = "/shuhua/"+painter.getId()+"/";;
					}
				}else{
					foldName = "/shuhua/";
				}
				String originalImgPath = absolutePath +foldName+image_id+"."+suffix ;//原图
				String bigImgPath = absolutePath+foldName+image_id +"_b."+suffix ;//大图
				String middleImgAPath = absolutePath+foldName+image_id +"_m_a."+suffix ;//列表页面中图
				String middleImgBPath = absolutePath+foldName+image_id +"_m_b."+suffix ;//中图2
				String smallImgPath = absolutePath+foldName+image_id +"_s."+ suffix ;//小图
				logger.info("originalImgPath==="+originalImgPath);
				writeImageinfo(imageInfo, originalImgPath);
				writeCiyiBigImgPath(originalImgPath, bigImgPath, sharpId);
				writeMiddleImageA(originalImgPath,middleImgAPath , sharpId);
				writeCiyiMiddleImageB(originalImgPath, middleImgBPath, sharpId);
				writeSmallImage(originalImgPath, smallImgPath, sharpId);
			}
			else if(  3 == catalogType.getId() ){ //瓷器
				String foldName = "/ciyi/";
				if( painter != null){
					foldName += painter.getId()+"/";
				}
				String originalImgPath = absolutePath +foldName+image_id+"."+suffix ;
				String bigImgPath = absolutePath+foldName+image_id +"_b."+suffix ;
				String middleImgAPath = absolutePath+foldName+image_id +"_m_a."+suffix ;
				String middleImgBPath = absolutePath+foldName+image_id +"_m_b."+suffix ;
				String smallImgPath = absolutePath+foldName+image_id +"_s."+ suffix ;
				logger.info("originalImgPath==="+originalImgPath);
				writeImageinfo(imageInfo, originalImgPath);
				writeCiyiBigImgPath(originalImgPath, bigImgPath, sharpId);
				writeMiddleImageA(originalImgPath,middleImgAPath , sharpId);
				writeCiyiMiddleImageB(originalImgPath, middleImgBPath, sharpId);
				writeSmallImage(originalImgPath, smallImgPath, sharpId);
		    }
		}else{
			String foldName = "/painting/";
			if( painter != null ){
				foldName += painter.getId()+"/";
			}
			String originalImgPath = absolutePath +foldName+image_id+"."+suffix ;//原图
			String middleImgAPath = absolutePath+foldName+image_id +"_m_a."+suffix ;//列表页面中图
			String smallImgPath = absolutePath+foldName+image_id +"_s."+ suffix ;//小图
			logger.info("originalImgPath==="+originalImgPath);
			writeImageinfo(imageInfo, originalImgPath);
			writeMiddleImageA(originalImgPath, middleImgAPath,sharpId);
			writeSmallImage(originalImgPath, smallImgPath,sharpId);
		}
	}
	
	private void writeSmallImageinfo(Painting painting,ImageInfo imageInfo) throws Exception {
		if(imageInfo == null) return ;
		
    	Long sharpId = imageInfo.getSharpId();
		long image_id = imageInfo.getId();
		String suffix = imageInfo.getSuffix();
		
		CatalogType catalogType = painting.getCatalogType();
		Painter painter = painting.getPainter();
		String absolutePath  = getImageGeneratePath();
		if( catalogType != null){
			if( 1 == catalogType.getId() ||  2 == catalogType.getId()){
				String foldName = "";
				if( painter != null ){
					if( "2".equals(painter.getType())){//名家名画
						foldName = "/painting/"+painter.getId()+"/";
						String originalImgPath = absolutePath +foldName+image_id+"."+suffix ;//原图
						String smallImgPath = absolutePath+foldName+image_id +"_s."+ suffix ;//小图
						logger.info("originalImgPath==="+originalImgPath);
						writeSmallImage(originalImgPath, smallImgPath,sharpId);
						return;
					}else{
						foldName = "/shuhua/"+painter.getId()+"/";;
					}
				}else{
					foldName = "/shuhua/";
				}
				String originalImgPath = absolutePath +foldName+image_id+"."+suffix ;//原图
				String smallImgPath = absolutePath+foldName+image_id +"_s."+ suffix ;//小图
				logger.info("originalImgPath==="+originalImgPath);
				writeSmallImage(originalImgPath, smallImgPath, sharpId);
			}
			else if(  catalogType.getId() >= 3  ){
				CatalogTypeManager catalogTypeManager = SpringContextHolder.getBean("catalogTypeManager");
				catalogType = catalogTypeManager.get(catalogType.getId());
				String foldName = "/"+catalogType.getEnglish_name()+"/";
				if( painter != null){
					foldName += painter.getId()+"/";
				}
				String originalImgPath = absolutePath +foldName+image_id+"."+suffix ;
				String smallImgPath = absolutePath+foldName+image_id +"_s."+ suffix ;
				logger.info("originalImgPath==="+originalImgPath);
				writeSmallImage(originalImgPath, smallImgPath, sharpId);
		    }
		}else{
			String foldName = "/painting/";
			if( painter != null ){
				foldName += painter.getId()+"/";
			}
			String originalImgPath = absolutePath +foldName+image_id+"."+suffix ;//原图
			String smallImgPath = absolutePath+foldName+image_id +"_s."+ suffix ;//小图
			logger.info("originalImgPath==="+originalImgPath);
			writeSmallImage(originalImgPath, smallImgPath,sharpId);
		}
	}

	/**
	 * 将数据库图片生成至指定路径
	 */
	private String writeImageinfo(ImageInfo img,String imgPath){
		   
	    	if(img == null) return null;
	    	
	    	if(img.getPhoto() == null){
	    		String newNameUploaded = img.getNewNameUploaded();
	    		if( newNameUploaded != null){
	    			FileUtil.copyFile(getImageUploadPath()+"/"+img.getNewNameUploaded(),imgPath);
	    			return imgPath;
	    		}
	    		return null;
	    	}
	    	
	    	InputStream is  = null;
	    	FileOutputStream fos = null;
			try {
				checkDirectory(imgPath);
				is = new ByteArrayInputStream(img.getPhoto().getData());
				fos = new FileOutputStream(imgPath);
				byte[] buf = new byte[1024];
				int len;
				while ((len = is.read(buf)) != -1) {
					fos.write(buf, 0, len);
				}
				return imgPath;
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			finally{
				if(fos != null){
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(is != null){
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			
			return null;
	    }
	
	private void checkDirectory(String filepath){
		assert(filepath.indexOf(".")>0);
		File dirFile = new File(filepath.substring(0,filepath.lastIndexOf("/")));
		if( !dirFile.exists()){
			dirFile.mkdirs();
		}
	}

}
